/**
 * This object handles all the communication with the server.
 *
 * options {
 *  url - the server url, defaults to the productive server
 * }
 *
 */
var ServerController = function (options) {

  var self = this;

  this.options = _.extend({
    url: 'http://193.26.192.141/mediaplatform/mediaplatform/'
  }, options);

  this._guuid = function () {

    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  };

  this._getSubtopicsTopicsFromResponse = function (topic) {
    var items = [];
    _.each(topic.subtopics, function (subTopic) {
      var item = new TopicDataModel(topic, subTopic);
    }, this);
    return items;
  };

  this._getTopicsFromResponse = function (rootTopic) {
    var items = [];
    if (rootTopic) {
      _.each(rootTopic.subtopics, function (topic) {
        items.push(this._getSubtopicsTopicsFromResponse(topic));
      }, this);
    }
    return items;
  };

  this._getDetailsFromResponse = function (data) {
    var items = [];

    _.each(data.resources, function (resource) {
      var item = new ResourceDataModel(resource);
      items.push(item);
    }, this);

//        var personItems = [];
//        _.each(data.persons, function (person) {
//            items.push(person);
//        }, this);

    return items;
  };

  this._handleServerResponse = function (data) {

    var topicItems = this._getTopicsFromResponse(data.topicsRoot, true);
    var detailItems = this._getDetailsFromResponse(data);

    // Sondefall!! Wenn nur eine Resource vom Server kommt,
    // gehören die Topics zu dieser Resource!
    if (detailItems.length == 1) {
      console.log("Only one resource " + detailItems[0].id + " add toppics");
      console.log(topicItems);
      detailItems[0].topics.add(topicItems);
      self.trigger("resources", detailItems);
    }
    else {
      if (detailItems.length > 0)
        self.trigger("resources", detailItems);

      if (topicItems.length > 0)
        self.trigger("topics", topicItems);
    }
  };

  /**
   * Calls the findByTopic function on the server.
   *
   * On success the provided callback is called
   */
  this.findRelatedTopics = function (id,type,callback) {
    var requestType = "";

    var request = {
      "_class_": "Request",
      "id": self._guuid(),
      "sessionId": this.sessionId,
      "application": "museum",
      "type": "findByTopic",
      "client": "Staedel",
      "topic": {
        "_class_": "Topic",
        type: type,
        reference: id
      }
    };

    $.ajax({
      type: "POST",
      url: self.options.url,
      data: JSON.stringify(request),
      processData: false,
      contentType: "application/json; charset=UTF-8",
      context: this,
      dataType: "json",
      success: function (data) {
        if(callback)
          callback(data)
      },
      error: function (request, textStatus, errorThrown) {
        this.trigger("error", request);
      }
    });

  };

  /**
   * Calls the findByTopic function on the server using the given topic
   *
   * On success a "resouces" event ist generated
   *
   * @param topic the topic, as it is delivered from the server
   */
  this.findByTopic = function (topic,callback) {

    var requestType = "";

    var request = {
      "_class_": "Request",
      "id": self._guuid(),
      "sessionId": this.sessionId,
      "application": "museum",
      "type": "findByTopic",
      "client": "Staedel",
      "topic": topic.serverData
    };

     console.log("findByTopic...");

    $.ajax({
      type: "POST",
      url: self.options.url,
      data: JSON.stringify(request),
      processData: false,
      contentType: "application/json; charset=UTF-8",
      context: this,
      dataType: "json",
      success: function (data) {
        console.log("success: findByTopic");
        if(callback)
          callback(data);
      },
      error: function (request, textStatus, errorThrown) {
        this.trigger("error", request)
      }
    });

  };


  /**
   * Calls the findByText function on the server using the given search string
   *
   * On success the provided callback is called
   *
   * @param searchString
   * @param callback
   */
  this.findByText = function (searchString,callback) {

    var request = {
      "_class_": "Request",
      "id": self._guuid(),
      "sessionId": this.sessionId,
      "application": "museum",
      "type": "findByText",
      "client": "Staedel",
      "text": searchString
    };

    $.ajax({
      type: "POST",
      url: self.options.url,
      data: JSON.stringify(request),
      processData: false,
      contentType: "application/json; charset=UTF-8",
      context: this,
      dataType: "json",
      success: function (data) {
//        console.log(data);
        if(callback)
          callback(data);
      },
      error: function (request, textStatus, errorThrown) {
        this.trigger("error", request)
      }
    });

  };

  /**
   * Calls the findByTopic function on the server
   *
   * On success a "features" event ist generated, which contains the feature topics.
   */
  this.getStartTopics = function () {

    var request = {
      "_class_": "Request",
      "id": self._guuid(),
      "sessionId": this.sessionId,
      "application": "museum",
      "client": "Staedel",
      "type": "getStartTopics"
    };

    $.ajax({
      type: "POST",
      url: self.options.url,
      data: JSON.stringify(request),
      processData: false,
      contentType: "application/json; charset=UTF-8",
      context: this,
      dataType: "json",
      success: function (data) {

        var topicItems = self._getTopicsFromResponse(data.topicsRoot);
        self.trigger("features", topicItems);
      },
      error: function (request, textStatus, errorThrown) {
        this.trigger("error", request)
      }
    });
  };


  /**
   * Calls the findByText function on the server using the given search string
   *
   * On success the provided callback is called
   *
   * @param searchString
   * @param callback
   */
  this.findLiteratureByText = function (searchString,callback) {

    var request = {
      "_class_": "Request",
      "id": self._guuid(),
      "sessionId": this.sessionId,
      "application": "library",
      "type": "findByText",
      "client": "Staedel",
      "text": searchString
    };

    $.ajax({
      type: "POST",
      url: self.options.url,
      data: JSON.stringify(request),
      processData: false,
      contentType: "application/json; charset=UTF-8",
      context: this,
      dataType: "json",
      success: function (data) {
        console.log(data);
        if(callback)
          callback(data);
      },
      error: function (request, textStatus, errorThrown) {
        this.trigger("error", request)
      }
    });

  };
}


